package com.czk.utils;

import com.czk.entity.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/12/15 17:06
 */
@Component
public class HtmlParseUtils {
    /**
     * jd搜索内容的的爬取实现
     *
     * @param keywords
     * @return
     * @throws IOException
     */
    public static List<Content> parseJD(String keywords) throws IOException {
        // 获取请求
        String url = "https://search.jd.com/Search?keyword=" + keywords;
        // 解析网页
        // document就是浏览器的树对象
        Document document = Jsoup.parse(new URL(url), 60 * 1000);
        //
        Element element = document.getElementById("J_goodsList");
        //
        Elements elements = element.getElementsByTag("li");
        List<Content> list = new ArrayList<>(10);
        for (Element el : elements) {
            // 获取图片
            // 关于图片特别多网站，所有的图片都是懒加载的
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            // 获取价格
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            Content content = new Content(title, img, price);
            list.add(content);
        }
        return list;
    }
}
